<template>
  <BasicModal centered destroyOnClose aria-hidden="false"
              v-bind="$attrs"
              :width="720"
              :bodyStyle="{overflowY:'hidden', height:'585px'}"
              :title="title"
              :canFullscreen="false"
              :maskClosable="false"
              @ok="handleOk"
              @register="registerModal"
  >
    <a-row :gutter="5" style="margin: 0; padding: 0">
      <a-col flex="248px" style="border: 1px #ddd solid;">
        <CustomerTree @onClick="onClick"/>
      </a-col>
      <a-col flex="455px" style="border: 1px #ddd solid; padding-top: 10px; margin-left: 5px">
        <a-form ref="registerForm" :model="model" :rules="validatorRules" :labelCol="{ span: 5 }" :wrapperCol="{ span: 17 }">
          <a-input type="hidden" v-model:value="model.id" />
          <a-form-item name="type" label="数据类型">
            <a-radio-group v-model:value="indexRegisterType" buttonStyle="solid" >
              <a-radio-button :value="TypeEnum.CITE" :disabled="indexRegisterType != TypeEnum.CITE">地区</a-radio-button>
              <a-radio-button :value="TypeEnum.COMP" :disabled="indexRegisterType != TypeEnum.COMP">单位</a-radio-button>
              <a-radio-button :value="TypeEnum.PERS" :disabled="indexRegisterType != TypeEnum.PERS">联系人</a-radio-button>
            </a-radio-group>
          </a-form-item>
          <a-form-item name="parentId" label="上级编号" v-show="items.type_kh || items.type_lxr">
            <a-input disabled class="formText" v-model:value="model.parentId" />
          </a-form-item>
          <a-form-item name="parentId" label="所属单位" v-show="items.type_kh || items.type_lxr">
            <a-input readonly class="formText" v-model:value="model.parentAreaName" />
          </a-form-item>
          <!--a-form-item label="所属部门" v-show="items.type_lxr">
            <Cascader 
              v-model:value="cascader.ids" 
              :options="cascader.options"
              :changeOnSelect="true"
              expandTrigger="hover"
              placeholder="请选择" 
              stringToNumber
              @change="changeCustomerDepart"
            />
            <a-input type="hidden" v-model:value="model.departId" />
          </a-form-item-->
          <a-form-item name="areaName" :label="items.customerText" v-show="items.type_cs || items.type_kh || items.type_lxr">
            <a-input type="text" class="formText" v-model:value="model.areaName" autoComplete="off"/>
          </a-form-item>
          <a-form-item name="lxdh" label="手机号码" v-show="items.type_lxr">
            <a-input type="text" v-model:value="model.lxdh" autoComplete="off" v-show="false"/>
            <JSelectEdit 
              :parentId="model.parentId" 
              :customerId="model.id"
              :customerType="model.Type"
              :showOptionList="true"
              selectStyle="width: 350px"
              @updateLxdh="updateLxdhCount"
            ></JSelectEdit>
          </a-form-item>
          <a-form-item label="单位地址" v-show="items.type_kh || items.type_lxr">
            <a-input type="text" class="formText " v-model:value="model.dwdz" />
          </a-form-item>
          <a-form-item label="工作QQ" v-show="items.type_lxr">
            <a-input type="text" class="w-150px" v-model:value="model.qq" />
          </a-form-item>
          <a-form-item label="微信号码" v-show="items.type_lxr">
            <a-input type="text" class="w-150px" v-model:value="model.wxh" />
          </a-form-item>
          <a-form-item label="传真号码" v-show="false">
            <a-input type="text" class="w-150px" v-model:value="model.czh" />
          </a-form-item>
          <a-form-item label="排序">
            <a-input type="number" class="w-150px" v-model:value="model.sort" :maxlength="5"/>
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
  </BasicModal>
</template>

<script lang="ts" setup>
import { computed, inject, nextTick, reactive, ref, unref } from "vue";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { customerSave, getCustomerById, TypeEnum, departSelect, departById } from "../customer.api";
import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import { useUserStore } from '/@/store/modules/user';
import { Cascader } from 'ant-design-vue';
import CustomerTree from "./CustomerTree.vue"
import JSelectEdit from '/@/components/Form/src/jeecg/components/JSelectEdit.vue';

const emit = defineEmits(["success", "register"]);
//接收表单对象
const registerForm = ref();
//表单控件
const items = reactive({
  type_cs: false,
  type_kh: false,
  type_lxr: true,
  customerText: "单位名称",
  action:'',
});
//单位部门
const cascader = reactive<any>({
  ids: [],
  options: [],
});

//是否为更新操作
const isUpdate = ref<boolean>(false);
const title = computed(() => isUpdate.value ? "编辑" : "新增");


//-------------------------------------
let selectedValue = reactive<any>("");
let options = reactive<any>([
  { value: 'apple', label: '苹果' },
  { value: 'banana', label: '香蕉' },
  { value: 'cherry', label: '樱桃' }
]);
//-------------------------------------



//表单数据
let model = reactive<any>({});
//数据类型，默认值
let indexRegisterType = ref<string>('1');

//自定义
let validateDepartId = async (rule, value) => {
  console.info("validateDepartId@@@", model.type, rule, value)
  if (model.type === '2' && !value) {
    return Promise.reject('不能为空!');
  } else {
    return Promise.resolve();
  }
};

//表单校验
const validatorRules = reactive<any>({
  type: [{ required: true, message: "不能为空!" }],
  parentId: [{ required: true, message: "不能为空!" }],
  areaName: [{ required: true, message: "不能为空!" }],
  lxdh: [
    {
      validator: (_, value) => {
        console.info("lxdh@@@@", value, model.type, model.lxdh)
        if (items.type_lxr && (!model.lxdh || Number(model.lxdh) === 0)) {
          return Promise.reject('手机号码不能为空!');
        }
        return Promise.resolve();
      },
      trigger: 'blur'
    }
  ],
  departId: [
    { required: true, message: "不能为空!" },
    {
      validator: (_, value) => {
        //console.info("departId@@@@", value)
        if (value === "-1") {
          return Promise.reject('数据选择错误！');
        } else {
          return Promise.resolve();
        }
      },
    }
  ],
});

/**
 * 定义组件变量
 */
const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
  setModalProps({ confirmLoading: false });
  resetFields()
  isUpdate.value = !!data?.isUpdate;
  let typeVal = 1;
  if (unref(isUpdate)) {
    //获取详情
    await getCustomerById({ id: data.record.id }).then((res) => {
      let name = res.pathName.split("|")
      res.parentAreaName = name[name.length - 2] || ''
      //表单赋值
      Object.assign(model, res);
      typeVal = Number(model.type)
    });
  }
  await changeType(typeVal)
    // 清除表单校验状态
  clearValidate();
});

//表单重置
function resetFields() {
  model.id = null;
  model.type = '';
  model.parentId = '';
  model.parentAreaName = '';
  model.departId = '';
  model.areaName = '';
  model.dwdz = '';
  model.lxdh = '';
  model.qq = '';
  model.wxh = '';
  model.gsdh = '';
  model.czh = '';
  model.sort = '';
}

// 提交事件 registerForm.value.
//const registerForm = ref();

async function handleOk() {
  await registerForm.value.validate().then(async () => {
    try {
      setModalProps({ confirmLoading: true });
      //提交表单
      await customerSave(items.action, model);
      closeModal();
      emit("success");
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }).catch((error: ValidateErrorEntity<any>) => {
    console.log("error", error);
  });
}

/**
 * 树节点点击事件
 * 当点城市 type = 0, 加1后 customer.type = 1 公司
 * @param treeNode
 * @returns {boolean}
 */
function onClick(treeNode) {
  var id = model.id;
  var dataVal = (Number(model.type) + 1);
  var typeVal = (Number(treeNode.type) + 1);     //点选节点属性
  //id有值时为更新，无时为添加
  if (id) {
    if (!dataVal) {
      console.info("dataVal = " + dataVal + ", 数据不符合规范，请检查。");
      return false;
    }
    //当前是地区  dataVal=1，上级目录不可变更
    //当前是公司  dataVal=2，上级目录只可变更到，地区下
    //当前是联系  dataVal=3，上级目录只可变更到，公司下
    //点选的要小于编辑的
    if (dataVal == 1 || (dataVal != (typeVal + 1))) {
      return false;
    }
  } else {

  }

  if (typeVal != undefined && typeVal != null && typeVal >= 0) {
    if (typeVal == 0) {
      // 添加城市
      model.type = typeVal;
      model.parentId = "";
      model.parentAreaName = "";
      changeType(typeVal);
    } else if (typeVal == 1) {
      // 添加公司
      model.type = typeVal;
      model.parentId = treeNode.id;
      model.parentAreaName = treeNode.name;
      changeType(typeVal);
    } else if (typeVal == 2) {
      // 添加联系人
      model.type = typeVal;
      model.parentId = treeNode.id;
      model.parentAreaName = treeNode.name;
      changeType(typeVal);
    } else if (typeVal == 3) {
      model.parentId = "";
      model.parentAreaName = "";
      model.areaName = "";
      model.lxdh = "";
      model.qq = "";
    }
  }
}

const userStoreTenantId = useUserStore().getTenant

function changeType(typeVal: number) {
  //alert($("#searchBoxx").val());
  model.type = typeVal;
  indexRegisterType.value = typeVal + ""
  //$("#searchBoxx").attr("disabled",true);
  if (typeVal == 0) {
    validatorRules.type[0].required = false;
    validatorRules.parentId[0].required = false;
    validatorRules.lxdh[0].required = false;
    validatorRules.departId[0].required = false;
    items.customerText = "城市：";
    items.type_kh  = false;
    items.type_lxr = false;
    items.type_cs  = true;
    items.action = "/customer/saveCity";
  } else if (typeVal == 1) {
    validatorRules.type[0].required = true;
    validatorRules.parentId[0].required = true;
    validatorRules.lxdh[0].required = false;
    validatorRules.departId[0].required = false;
    items.customerText = "单位名称：";
    items.type_cs  = false;
    items.type_lxr = false;
    items.type_kh  = true;
    items.action = "/customer/saveDirectory";
  } else if (typeVal == 2) {
    validatorRules.type[0].required = true;
    validatorRules.parentId[0].required = true;
    validatorRules.lxdh[0].required = true;
    if (userStoreTenantId == 1) {
      validatorRules.departId[0].required = true;
    } else {
      validatorRules.departId[0].required = false;
    }
    items.customerText = "联系人：";
    items.type_cs  = false;
    items.type_kh  = false;
    items.type_lxr = true;
    items.action = "/customer/save";
    cascaderCustomerDepart(model.parentId, model.departId);
  }
}

/**
 * 加载单位部门信息
 * qindl
 * 2023-07-31
 * @param id
 */
async function cascaderCustomerDepart(parentId, departId) {
  let params = { id: parentId }
  await departSelect(params).then((res) => {
    Object.assign(cascader.options, res);
  });

  if (!departId) {
    cascader.ids = []
    model.departId = ''
    return false;
  }

  //查部门/try catch 处理，不然编辑有问题
  await departById({ id: departId }).then((res) => {
    const departPath = res.path && res.path.split(",")
    const arrays = departPath <= 0 ? [] : departPath.filter(item => item) //[366,381,382]//e
    Object.assign(cascader.ids, arrays);
  });

}

function changeCustomerDepart(value) {
  //console.info("changeCustomerDepart@@@@", value, !value , value.length < 2)
  if (!value || value.length < 2) {
    model.departId = "-1"
  } else {
    model.departId = value[1];
  }
}

// 定义清除校验状态的方法
const clearValidate = async (nameList?: string | string[]) => {
  if (registerForm.value) {
    try {
      await registerForm.value.clearValidate(nameList);
      console.log('表单校验状态已清除');
    } catch (error) {
      console.error('清除表单校验状态失败:', error);
    }
  }
};

/**
 * 更新联系人数
 * @param count
 */
function updateLxdhCount(count) {
  model.lxdh = count;
  console.log('更新后的 model.lxdh:', model.lxdh);
  clearValidate("lxdh");
};

</script>

<style scoped lang="less">

.jeecg-basic-tree {
  border: 1px green solid;
  overflow: auto;

  ::v-deep(.ant-tree) {
    li {
      padding: 0 !important;
    }
  }
}

</style>
